package com.xy.blog.core.springmvc.controller;

import com.xy.blog.core.exception.contants.SuccessCode;
import com.xy.blog.core.springmvc.result.base.data.BaseDataResult;
import com.xy.blog.core.springmvc.result.base.page.BasePageResult;
import com.xy.blog.core.springmvc.result.base.page.Page;
import com.xy.blog.core.springmvc.result.page.PageResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

import java.util.Locale;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description: 基础BaseController
 * @date 2020/3/3
 */
public class BaseController {

    @Autowired
    private MessageSource messageSource;

    /**
     * 返回基础数据
     * @param data
     * @return
     */
    public Object getData(Object data) {
        return getData(true, data, SuccessCode.OK, new String[]{});
    }

    /**
     * 返回成功
     * @return
     */
    public Object success(){
        return getData(true, "" , SuccessCode.OK, new String[]{});
    }

    /**
     * 返回基础数据
     * @param success
     * @param data
     * @param code
     * @param args
     * @return
     */
    public Object getData(Boolean success, Object data, String code, String[] args) {
        String message = messageSource.getMessage(code, args, Locale.getDefault());
        BaseDataResult<Object> baseDataResult = new BaseDataResult<>();
        baseDataResult.setCode(code);
        baseDataResult.setMessage(message);
        baseDataResult.setData(data);
        baseDataResult.setSuccess(success);
        return baseDataResult;
    }


    /**
     * 返回分页数据
     * @param result
     * @return
     */
    public Object getPageData(PageResp result) {
        return getPageData(true, result, SuccessCode.OK, new String[]{});
    }

    /**
     * 返回分页数据
     * @param success
     * @param resp
     * @param code
     * @param args
     * @return
     */
    public Object getPageData(Boolean success, PageResp resp, String code, String[] args) {
        BasePageResult<Object> basePageResult = new BasePageResult<Object>();
        String message = messageSource.getMessage(code, args, Locale.getDefault());
        Page page = new Page();
        page.setPageNo(resp.getPageNo());
        page.setPages(resp.getPages());
        page.setPageSize(resp.getPageSize());
        page.setTotal(resp.getTotal());
        page.setHasPrev(resp.isHasPrev());
        page.setHasNext(resp.isHasNext());

        basePageResult.setPage(page);
        basePageResult.setCode(code);
        basePageResult.setData(resp.getList());
        basePageResult.setMessage(message);
        basePageResult.setSuccess(success);
        return basePageResult;
    }
}